package com.okok.service;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

import com.common.springside.DateProvider;
import com.common.springside.Digests;
import com.common.springside.Encodes;
import com.entity.myInterface.RoleRepository;
import com.entity.myInterface.UserDao;
import com.okok.entity.User;
import com.shiro.entity.Role;
import com.shiro.services.AbstractService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
//import org.springside.modules.utils.DateProvider;



/**
 * 用户管理类
 * @author Eason
 *
 */
// Spring Service Bean的标识.
@Component
public class AccountService extends AbstractService {

	public static final String HASH_ALGORITHM = "SHA-1";
	public static final int HASH_INTERATIONS = 1024;
	private static final int SALT_SIZE = 8;

	private static Logger logger = LoggerFactory.getLogger(AccountService.class);

	@Autowired
	RoleRepository roleRepository;

	/*@Autowired
	private UserRepository userRepository;*/

	@Autowired
	private UserDao userDao;

	private DateProvider dateProvider = DateProvider.DEFAULT;

	public List<User> getAllUser() {
		return (List<User>) userDao.findAll();
	}

    public Optional<User> getUser(String id) {
        return userDao.findById(id);
    }

    public Optional<User> findCurrentUser(){
        return userDao.findById(getCurrenUserId());
    }

	public User findUserByLoginName(String loginName) {
		return userDao.findByLoginName(loginName);
	}

	// APP,PC校验是否存在用户问题
	public User findUserByLoginNameAndDelflag(String loginName) {
		return userDao.findUserByLoginNameAndDelflag(loginName, "okok");
		
	}

	public User findUserByEmail(String email){
		return userDao.findByEmail(email);
	}

	/**
	 * 用户注册
	 * @param user
	 * @author Eason
	 */
	public void registerUser(User user) {
		entryptPassword(user);
		/*List<Role> list = new ArrayList<Role>();
		//根据用户选择的注册类型提供两类用户的角色用来显示认证的类型	
		Role role = new Role(roleRepository.findByCode("customer").getId());
		list.add(role);*/
		//为了区分新老用户加个新用户角色
		//role = new Role(roleRepository.findByCode("newuser").getId());
		//list.add(role);

		user.setRegisterDate(dateProvider.getDate());
		user.setApp("okok");
		user.setPlainPassword(null);
		userDao.save(user);
	}

	/**
	 * 用户登录
	 * @param user
	 * @param password
	 * @return
	 * @author Eason
	 */
	public Boolean login(User user, String password) {
		byte[] salt = Encodes.decodeHex(user.getSalt());
		String hashPass = this.hashPassword(password, salt);
	    return user.getLoginPwd().equals(hashPass);
	}
	
/*
	public void updateUser(User user) {
		if (StringUtils.isNotBlank(user.getPlainPassword())) {
			entryptPassword(user);
		}
		userDao.save(user);
	}

	public void deleteUser(String id) {
		if (isSupervisor(id)) {
			logger.warn("操作员{}尝试删除超级管理员用户", getCurrentUserName());
			throw new ServiceException("不能删除超级管理员用户");
		}
		userDao.delete(id);

	}*/

	/**
	 * 判断是否超级管理员.
	 */
	private boolean isSupervisor(String id) {
		return id.equalsIgnoreCase("1");
	}
	

	/**
	 * 设定安全的密码，生成随机的salt并经过1024次 sha-1 hash
	 */

	private void entryptPassword(User user) {
		byte[] salt = Digests.generateSalt(SALT_SIZE);
		user.setSalt(Encodes.encodeHex(salt));

		byte[] hashPassword = Digests.sha1(user.getPlainPassword().getBytes(), salt, HASH_INTERATIONS);
		user.setLoginPwd(Encodes.encodeHex(hashPassword));
	}

	@Autowired
	public void setUserDao(UserDao userDao) {
		this.userDao = userDao;
	}

	/**
	 * 
	 * @param user
	 * @param newpass
	 */
	public void resetPassword(User user,  String newpass, String op) {
		byte[] salt = Encodes.decodeHex( user.getSalt() );
		String hashPass = this.hashPassword(newpass, salt);
		
		this.userDao.resetPass(user, op,  hashPass);
	}
	

	private String hashPassword(String plainPassword, byte[] salt) {
		byte[] hashPassword = Digests.sha1(plainPassword.getBytes(), salt, HASH_INTERATIONS);
		String strHashPassword = Encodes.encodeHex(hashPassword);
		return strHashPassword;
	}
/*
	public ActionResult updatePassword(String oldPassword,String newPwd) {
		
		if (StringUtils.isBlank(oldPassword)){
			return new ActionResult("", Const._INT_FALSE, "", "旧密码不存在", null);
		}
		
		User user=userRepository.findById(getCurrentUser().getId());
		if(!this.login(user,oldPassword)){
			logger.info("in login");
			return new ActionResult( "", Const._INT_FALSE, "", "旧密码错误", "" );
		}
		
		if (StringUtils.isBlank(newPwd)){
			return new ActionResult("", Const._INT_FALSE, "", "新密码不存在", "1");
		}
		
		this.resetPassword(user, newPwd, getCurrentUser().getLoginName());
		
		return new ActionResult( "", Const._INT_TRUE, "", Const._OK_UP_PASS, "" );
	}


	public ActionResult adResetPassword(String id) {
		
		if (StringUtils.isBlank(id)){
			return new ActionResult("", Const._INT_FALSE, "", "用户名未填", null);
		}
		
		User user=userRepository.findById(id);
		if (user==null){
			return new ActionResult("", Const._INT_FALSE, "", "用户不存在", null);
		}
		this.resetPassword(user, "123123", getCurrentUser().getLoginName());
		
		return new ActionResult( "", Const._INT_TRUE, "", "密码重置成功", "" );
	}*/

}
